import { defineStore } from 'pinia'
import { ref } from 'vue'
import i18n from '../i18n'
import { configApi } from '../api/config';

export const useAppStore = defineStore('app', () => {
    // 主题设置
    const theme = ref(localStorage.getItem('theme') || 'light')
    const setTheme = (newTheme: 'light' | 'dark') => {
        theme.value = newTheme
        localStorage.setItem('theme', newTheme)
        // 更新HTML元素的class
        if (newTheme === 'dark') {
            document.documentElement.classList.add('dark')
        } else {
            document.documentElement.classList.remove('dark')
        }
    }

    // 语言设置
    const locale = ref<string>(localStorage.getItem('locale') || 'zh')
    const setLocale = (newLocale: 'zh' | 'en') => {
        locale.value = newLocale
        localStorage.setItem('locale', newLocale)

        // 动态更新i18n的locale，使语言切换立即生效
        i18n.global.locale.value = newLocale
    }

    // 初始化主题
    const initTheme = () => {
        if (theme.value === 'dark') {
            document.documentElement.classList.add('dark')
        } else {
            document.documentElement.classList.remove('dark')
        }
    }
    const getConfig = async () => {
        const configData = ref({})
        try {
            const response = await configApi.getConfig();
            console.log('Configs response:', response);
            configData.value = response
        } catch (error) {
            console.error('Error fetching configs:', error);
        }
    }

    return {
        theme,
        setTheme,
        locale,
        setLocale,
        initTheme,
        getConfig
    }
})